﻿using Microsoft.Extensions.Options;
using ModelDto;
using StackExchange.Redis;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Common.achieve
{
    public class RedisHelper : IRedisHelper
    {
        private readonly IOptions<SystemAppSettings> _options;

        public ConnectionMultiplexer redis { get; set; }
        public IDatabase db { get; set; }
        public RedisHelper(IOptions<SystemAppSettings> options)
        {
            _options = options;
            redis = ConnectionMultiplexer.Connect(_options.Value.ConnectionRedis);
            db = redis.GetDatabase(0);
        }
        public bool DeleteKey(string key)
        {
            return db.KeyDelete(key);
        }

        public string GetValue(string key)
        {
            return db.StringGet(key);
        }

        public bool SetValue(string key, string value, TimeSpan? expiry = null)
        {
            return db.StringSet(key, value, expiry);
        }

        //计数器
        public long IncrementCounter(string key)
        {
            return db.StringIncrement(key);
        }

        // 获取计数的当前值
        public long GetCounterValue(string key)
        {
            RedisValue value = db.StringGet(key);

            if (value.HasValue)
            {
                return (long)value;
            }

            return 0;
        }
    }
}
